<template>
  <el-dialog :title="props.title" v-model="state.open" width="400px" append-to-body>
    <el-upload ref="uploadRef" :limit="1" :accept="props.accept" action="/" :disabled="realDisabled"
      :on-progress="bindFileUploadProgress" :on-error="bindError" :on-success="bindFileSuccess"
      :http-request="bindUpFileFun" :auto-upload="false" drag>
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div v-show="props.showUpdateSupport" class="el-upload__tip">
            <el-checkbox v-model="state.updateSupport" :true-value="1" :false-value="0" />是否更新已经存在的{{
              props.updateSupportText }}数据
          </div>
          <span>仅允许导入{{ props.accept }}格式文件。</span>
          <el-link v-show="props.templateConfig.uri" type="primary" :underline="false"
            style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="state.open = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="customImport">
const props = defineProps({
  /* 禁止上传文件 */
  disabled: {
    type: Boolean,
    default: false
  },
  accept: {
    type: String,
    default: '.xls,.xlsx'
  },
  /* 弹窗标题 */
  title: {
    type: String,
    default: ""
  },
  /* 是否显示更新支持 */
  showUpdateSupport: {
    type: Boolean,
    default: false
  },
  updateSupportText: {
    type: String,
    default: ''
  },
  /* 模板文件下载地址 */
  templateConfig: {
    type: Object,
    default: () => ({
      uri: '',
      title: '模板文件', // 文件名称或获取文件名称函数
      params: {}
    })
  },
  /* 自定义上传数据 */
  otherData: {
    type: Object,
    default: () => ({})
  },
  /* 上传接口 入参 {params, data, backProgress} */
  request: Function,
  /* 是否显示上传成功的返回消息框 */
  showMessage: {
    type: Boolean,
    default: true
  }
})
const state = reactive({
  open: false,
  updateSupport: 0,
  isUploading: false
})
const emit = defineEmits(['success'])
const realDisabled = computed(() => props.disabled || state.isUploading);
const { proxy } = getCurrentInstance();
/** 下载模板操作 */
function importTemplate() {
  proxy.download(props.templateConfig.uri, props.templateConfig.params, typeof props.templateConfig.title === 'function' ? props.templateConfig.title() : props.templateConfig.title);
};

/**文件上传中处理 */
const bindFileUploadProgress = (event, file, fileList) => {
  state.isUploading = true;
};
const bindError = (err, file, fileList) => {
  state.isUploading = false;
};

/** 文件上传成功处理 */
const bindFileSuccess = (response, file, fileList) => {
  state.open = false;
  state.updateSupport = 0
  state.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  props.showMessage && proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  emit("success", true)
};
const bindUpFileFun = (option) => {
  const params = Object.assign({}, props.otherData, {
    updateSupport: state.updateSupport
  });
  props.request({
    params: params,
    data: {
      file: option.file
    },
    backProgress: (e) => {
      if (e.total > 0) {
        e.percent = e.loaded / e.total * 100
      }
      option.onProgress(e)
    }
  }).catch((e) => {
    option.onError(e)
  })
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
defineExpose({
  open: () => {
    state.open = true;
  }
});
</script>

<style lang="scss" scoped></style>